package com.jn.servicedemo.views;

import android.animation.ObjectAnimator;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.jn.servicedemo.R;
import com.jn.servicedemo.constant.Constants;
import com.jn.servicedemo.event.MusicEvent;
import com.jn.servicedemo.service.CustomService;
import com.jn.servicedemo.widget.CircleImageView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class MusicActivity extends AppCompatActivity implements View.OnClickListener, SeekBar.OnSeekBarChangeListener {
   private Button mLast;
   private Button mPlay;
   private Button mNext;
   public CircleImageView mIvMusic;
   private boolean mPlaying = true;
   private MyServiceConnection mConnection;
   private CustomService mService;
   private ObjectAnimator animator;
   private SeekBar pbProgress;//播放进度条
   private TextView mTimeView;//展示播放时间
   private TextView tvBottomTitle;//名字
   private TextView tvBottomArtist;//作者
   private ImageView ivAlbumThumbnail;//歌曲图标
   private int mDuration;//总进度(总时间)
   public static final int UPDATE_PROGRESS = 1;

   @Override
   protected void onCreate(@Nullable Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_music);
      mLast = findViewById(R.id.last);
      mPlay = findViewById(R.id.play);
      mNext = findViewById(R.id.next);
      mIvMusic = findViewById(R.id.iv_music);
      mLast.setOnClickListener(this);
      mPlay.setOnClickListener(this);
      mNext.setOnClickListener(this);
      mConnection = new MyServiceConnection();
      Intent intent = new Intent(this, CustomService.class);
      bindService(intent, mConnection, BIND_AUTO_CREATE);
      animator = ObjectAnimator.ofFloat(mIvMusic,"rotation",0f,360.0f);
      animator.setDuration(10000);    //动画旋转一周的时间为10秒
      animator.setInterpolator(new LinearInterpolator());
      animator.setRepeatCount(-1);    //-1表示设置动画无限循环
      animator.start();
      tvBottomTitle = findViewById(R.id.tv_bottom_title);
      tvBottomArtist = findViewById(R.id.tv_bottom_artist);
      ivAlbumThumbnail = findViewById(R.id.iv_thumbnail);
      ivAlbumThumbnail.setOnClickListener(this);
      pbProgress = findViewById(R.id.progress);
      pbProgress.setOnSeekBarChangeListener(this);
      mTimeView = findViewById(R.id.time);
   }

   public String formatTime(int timeInMs) {
      int totalSeconds = timeInMs / 1000;
      int minutes = totalSeconds / 60;
      int seconds = totalSeconds % 60;
      return String.format("%02d:%02d", minutes, seconds);
   }


   @Subscribe(threadMode = ThreadMode.MAIN)
   public void onMusicInfoChangedEvent(MusicEvent event) {
      if ("infoChanged".equals(event.getMessage())) {
         updateMusicInfo();
      }
   }

   @Override
   protected void onStart() {
      super.onStart();
      EventBus.getDefault().register(this);
   }

   @Override
   protected void onStop() {
      super.onStop();
      EventBus.getDefault().unregister(this);
   }


   @Override
   public void onClick(View v) {
      sendCommand2(v.getId());
   }

   private void sendCommand(int id) {
      Intent intent = new Intent(this, CustomService.class);
      String command = null;
      if (id == R.id.last) {
         command = Constants.COMMAND_LAST;
      } else if (id == R.id.next) {
         command = Constants.COMMAND_NEXT;
      } else if (id == R.id.play) {
         if (mPlaying) {
            command = Constants.COMMAND_PAUSE;
            mPlay.setText("play");
            mPlaying = false;
         } else {
            command = Constants.COMMAND_PLAY;
            mPlay.setText("pause");
            mPlaying = true;
         }
      }
      intent.putExtra("command", command);
      startService(intent);
   }

   private void sendCommand2(int id) {
      if (mService == null) {
         return;
      }
      if (id == R.id.last) {
         mService.last();
         updateMusicInfo();
      } else if (id == R.id.next) {
         mService.next();
         updateMusicInfo();
      } else if (id == R.id.play) {
         if (mPlaying) {
            mService.pause();
            mPlay.setText("play");
            mPlaying = false;
            animator.pause();
         } else {
            mService.play();
            mPlay.setText("pause");
            mPlaying = true;
            animator.start();
         }
      }
   }




   @Subscribe(threadMode = ThreadMode.MAIN)
   public void onMusicEvent(MusicEvent event) {
      String msg = event.getMessage();
      Log.d("asdf", "onMusicEvent msg === " + msg);
      if (msg.equals("play")) {
         if (mService != null) {
            mDuration = mService.getDuration();
            Log.d("asdf", "总时长:" + mDuration);
            pbProgress.setMax(mDuration);
            new Thread(new MusicProgressRunnable()).start();
         }
      }
   }

   //@Override
   public void onPlayStart() {
      if (mService != null) {
         mDuration = mService.getDuration();
         Log.d("asdf", "总时长:" + mDuration);
         pbProgress.setMax(mDuration);
         mTimeView.setText(formatTime(0) + "/" + formatTime(mDuration));
         new Thread(new MusicProgressRunnable()).start();
      }
   }

   private Handler mHandler = new Handler(Looper.getMainLooper()) {
      public void handleMessage(Message msg) {
         switch (msg.what) {
            case UPDATE_PROGRESS:
               int position = msg.arg1;
               int duration = msg.arg2;
               pbProgress.setProgress(position);//设置当前进度(当前时间)
               //mTimeView.setText(position + "/" + mDuration);// 当前时间/总时间
               mTimeView.setText(formatTime(position) + "/" + formatTime(duration));// 当前时间/总时间
               break;
            default:
               break;
         }
      }
   };



   private class MusicProgressRunnable implements Runnable {
      public MusicProgressRunnable() {
      }

      @Override
      public void run() {
         boolean mThreadWorking = true;
         while (mThreadWorking) {
            try {
               if (mService != null) {
                  int position = mService.getCurrentPosition();
                  int duration = mService.getDuration();
                  //Log.d("asdf", String.valueOf(position));
                  Message message = new Message();
                  message.what = UPDATE_PROGRESS;
                  message.arg1 = position;
                  message.arg2 = duration;
                  mHandler.sendMessage(message);
               }
               mThreadWorking = mService.isPlaying();
               Thread.sleep(100);
            } catch (Exception e) {
               e.printStackTrace();
            }
         }
      }
   }




   private void updateMusicInfo() {
      if (mService != null) {
         String title = mService.getCurrentTitle();
         String artist = mService.getCurrentArtist();
         if (title != null && artist != null) {
            tvBottomTitle.setText(title);
            tvBottomArtist.setText(artist);
         }
      }
   }

   @Override
   public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
      if (mService != null && fromUser) {
         mService.seekTo(progress);//拖动进度条，改变播放进度
      }
   }

   @Override
   public void onStartTrackingTouch(SeekBar seekBar) {

   }

   @Override
   public void onStopTrackingTouch(SeekBar seekBar) {

   }

   private class MyServiceConnection implements ServiceConnection {

      @Override
      public void onServiceConnected(ComponentName name, IBinder service) {
         mService = ((CustomService.MyBinder) service).getService();
         mService.play();
         updateMusicInfo();
      }

      @Override
      public void onServiceDisconnected(ComponentName name) {
         mService = null;
      }
   }
}
